package com.ljxy.score.controller.myController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljxy.score.common.Result;
import com.ljxy.score.entity.LoginDto;
import com.ljxy.score.entity.User;
import com.ljxy.score.util.MD5Util;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class LoginController {


    @Resource
    private com.ljxy.score.service.userService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        if (loginDto == null) {
            return Result.error();
        }
        String captchaFromRedis = stringRedisTemplate.opsForValue().get("captcha");
        String code = (String) request.getSession().getAttribute("captcha");
        if (!code.equalsIgnoreCase(loginDto.getCode())) {
            return Result.error();
        }
        int count = userService.count(new QueryWrapper<User>().eq("account", loginDto.getPhone()));
        if (count == 0) {
            User user = new User();
            user.setAccount(loginDto.getPhone());
            String newPassword = MD5Util.string2MD5(loginDto.getPassword());
            user.setPassword(newPassword);
            userService.save(user);
            //注册成功
            return Result.success(200);
        }
        int count2 = userService.count(new QueryWrapper<User>().eq("account", loginDto.getPhone()).
                eq("password", MD5Util.string2MD5(loginDto.getPassword())));
        if (count2 != 0) {
            //登陆成功
            return Result.success(201);
        }
        return Result.error();
    }
}
